package com.ybfenpan.servlet;

import com.ybfenpan.taglib.annotation.Token;
import com.alibaba.fastjson.JSONObject;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.lang.reflect.Method;
import java.util.UUID;

/**
 * Created by Administrator on 2016/3/27.
 *用法是：在需要生成token的controller上增加@Token(save=true)，而在需要检查重复提交的controller上添加@Token(remove=true)就可以了。
 * 另外，你需要在form里增加下面代码：
 * <input type="hidden" name="token" value="${token}" />
 */
public class TokenInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (handler instanceof HandlerMethod) {
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            Method method = handlerMethod.getMethod();
            Token annotation = method.getAnnotation(Token.class);
            if (annotation != null) {
                if (annotation.save()) {
                    request.getSession(false).setAttribute("token", UUID.randomUUID().toString());
                }
                if (annotation.remove()) {
                    if (isRepeatSubmit(request)) {
                    	if (null != method.getAnnotation(ResponseBody.class)) {
                    		response.setHeader("Charset", "UTF-8");
                			response.setCharacterEncoding("UTF-8");
                			response.setContentType("application/Json;charset=utf-8");
                            PrintWriter out = response.getWriter();
                            JSONObject jo = new JSONObject();
                            jo.put("success", false);
                            jo.put("msg","表单已提交，请确认是否重复提交!如果没有，请稍后提交。");
                            out.print(jo.toString());
                            out.flush();
                            out.close();
                    	}
                        return false;
                    }
                    request.getSession(false).removeAttribute("token");
                }
            }
            return true;
        } else {
            return false;
        }
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }

    private boolean isRepeatSubmit(HttpServletRequest request) {
        String serverToken = (String) request.getSession(false).getAttribute("token");
        if (serverToken == null) {
            return true;
        }
        String clinetToken = request.getParameter("token");
        if (clinetToken == null) {
            return true;
        }
        if (!serverToken.equals(clinetToken)) {
            return true;
        }
        return false;
    }
}
